#include "gamehall.h"
#include "Player.h"

IGameHall::IGameHall()
{
    m_pMainStation = NULL;
    m_hMainStationDll = NULL;
}

IGameHall::~IGameHall(void)
{
    Release();
}

bool IGameHall::Initialize(LPCTSTR stationfile,LPCTSTR servercon,HWND hReciver,DWORD nRecv,DWORD nClose)
{
    IeoStringA constr = servercon;
    if(constr.FindNocase("proxy:") == IeoConst::NULL_POS)
        constr = m_ProxyString + _S(",") + servercon;
    if(m_pMainStation != NULL)
    {
        if( m_pMainStation->Initialize(constr) )
        {
            m_pMainStation->SetReceiver(hReciver,nRecv,nClose);
            return true;
        }
        return false;
    }

    IeoString file = IeoFile::GetFullFileName( stationfile );
    m_hMainStationDll = LoadLibrary(file);//LoadLibraryEx(file,NULL,LOAD_WITH_ALTERED_SEARCH_PATH);
    if( m_hMainStationDll == NULL )
        return false;
    
    CREATESTATION create = (CREATESTATION)GetProcAddress(m_hMainStationDll,"Create");
    if(create == NULL)
    {
        FreeLibrary(m_hMainStationDll);
        m_hMainStationDll = NULL;
        return false;
    }

    try
    {
        m_pMainStation = create();
        if(NULL == m_pMainStation)
        {
            FreeLibrary(m_hMainStationDll);
            m_hMainStationDll = NULL;
            return false;
        }

        if( m_pMainStation->Initialize(constr) )
        {
            m_pMainStation->SetReceiver(hReciver,nRecv,nClose);
            return true;
        }

        return false;

    }
    catch(...)
    {
        FreeLibrary(m_hMainStationDll);
        m_hMainStationDll = NULL;
        return false;
    }
}

void IGameHall::Release()
{
    if(m_pMainStation)
    {
        m_pMainStation->Release();
        m_pMainStation = NULL;
    }

    if(m_hMainStationDll)
    {
        FreeLibrary(m_hMainStationDll);
        m_hMainStationDll = NULL;
    }
}

bool IGameHall::SendPacket(const void *data,size_t size)
{
    _DEBUG_CHECK(m_pMainStation);
    return m_pMainStation->SendPacket(data,size);
}

void*IGameHall::PeekPacket(void **data,size_t *size)
{
    _DEBUG_CHECK(m_pMainStation);
    return m_pMainStation->PeekPacket(data,size);
}

void IGameHall::RemovePacket(void *handle)
{
    _DEBUG_CHECK(m_pMainStation);
    return m_pMainStation->RemovePacket(handle);
}